package yicr.untils;



import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NslUtilString {

    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /** 7位ASCII字符，也叫作ISO646-US、Unicode字符集的基本拉丁块      */
    public static final String US_ASCII = "US-ASCII";
    /** ISO拉丁字母表 No.1，也叫做ISO-LATIN-1     */
    public static final String ISO_8859_1 = "ISO-8859-1";
    /** 8 位 UCS 转换格式     */
    public static final String UTF_8 = "UTF-8";
    /** 16 位 UCS 转换格式，Big Endian(最低地址存放高位字节）字节顺序     */
    public static final String UTF_16BE = "UTF-16BE";
    /** 16 位 UCS 转换格式，Litter Endian（最高地址存放地位字节）字节顺序     */
    public static final String UTF_16LE = "UTF-16LE";
    /** 16 位 UCS 转换格式，字节顺序由可选的字节顺序标记来标识     */
    public static final String UTF_16 = "UTF-16";
    /** 中文超大字符集     **/
    public static final String GBK = "GBK";

    public static final String GB2312 = "GB2312";

    public static  String left(String s,int number){
        if(number<=0){
            throw  new RuntimeException("error : number < = 0");
        }
        if (isNullOrEmpty(s)) {
            return s;
        }
        int length=s.length();
        if(number>=length){
            return s;
        }
        return s.substring(0,number);
    }

    public static  String right(String s,int number){
        if(number<=0){
            throw  new RuntimeException("error : number < = 0");
        }
        if (isNullOrEmpty(s)) {
            return s;
        }
        int length=s.length();
        if(number>=length){
            return s;
        }
        return s.substring(length-number,length);
    }

    public static boolean compareIgnoreCaseAndSpace(String w1,String w2){
        if(w1==null || w2==null){
            throw  new NullPointerException("At least one of parameters is null.");
        }
        w1=w1.trim();
        w2=w2.trim();
        return w1.compareToIgnoreCase(w2)==0;
    }


    public static boolean isNullOrEmpty(String s) {
        if(s==null)
            return true;
        if(s.trim().equals("")){
            return true;
        }
        return false;
    }

    /**
     * @param array
     * @return
     */
    public static boolean isNullOrEmpty(String... array) {
        if(array==null){
            return true;
        }
        if(array.length==0){
            return true;
        }
        for(String s:array){
            if(!isNullOrEmpty(s)){
                return false;
            }
        }
        return true;
    }

    /**
     * 根据length;删除字符串最后几位，返回截取后的字符串
     * @param  s 待处理字符串
     * @param  length 拟删除长度,必须大于0
     * @return String     返回截取后的字符串
     */
    public static String deleteTail(String s,int length){
		/*if(s==null){
			return null;
		}*/
        if(s.equals("")){
            return s;
        }
        if(length<0){
            throw new RuntimeException("p:length has error ;");
        }
        if(length>=s.length()){
            return "";
        }
        return s.substring(0, s.length()-length);
    }

    public static String deleteTail(StringBuffer sb,int length){
        return deleteTail(sb.toString(), length);
    }


    public static List<Long> string2LongList(String s, String dividor){
        List<Long> list=new ArrayList<>();
        if(!isNullOrEmpty(s)){
            String[] arrayString=s.split(dividor);
            for(String string:arrayString){
                Long l=Long.parseLong(string);
                list.add(l);
            }
        }
        return list;
    }

    public static List<Integer> string2IntegerList(String s,String dividor){
        List<Integer> list=new ArrayList<>();
        if(!isNullOrEmpty(s)){
            String[] arrayString=s.split(dividor);
            for(String string:arrayString){
                Integer l=Integer.parseInt(string);
                list.add(l);
            }
        }
        return list;
    }

    /**
     * @param source
     * @param token
     * @return
     */
    static public String surround(String source,String token){
        if (isNullOrEmpty(source)) {
            return source;
        }
        return token+source+token;
    }





    /**
     * 输入 a,b,c ，获得 c
     * @param sourceString
     * @param separator
     * @return
     */
    public static String getLastFragment(String sourceString,String separator){
        int lastIndex=sourceString.lastIndexOf(separator);
        if(lastIndex==-1){
            return sourceString;
        }else{
            return sourceString.substring(lastIndex+1);
        }
    }

    /**
     * 判断不为空，且 string 不为 trim后的 空字符串
     */
    public static boolean notNullAndTrimBlank(String s){
        return s !=null && !s.trim().equals("");
    }


    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 首字母 变大写
     * @param s
     * @return
     */
    public static String upperCaseFirstLetter(String s){
        if(s==null || s.trim().equals("")){
            return s;
        }
        s=s.trim();
        String first=s.substring(0,1);
        String left=s.substring(1,s.length());
        return first.toUpperCase()+left;
    }

    /**
     * 对传入的 s，根据编码类型，去除bom
     * @return
     */
    public static String removeBomOfString(String s, NslEnumFileCharSet fileCharSet){
        String output;
        switch (fileCharSet){
            case UTF8_BOM:output=removeBytes(s,0,2);break;
            case UTF16LE_BOM:;
            case UTF16BE_BOM:output=removeBytes(s,0,2);break;
            case UTF32BE_BOM:;
            case UTF32LE_BOM:output=removeBytes(s,0,3);break;
            default:output=s;
        }
        return output;
    }

    /**
     * 将string去除指定的区域的字节，返回剩余bytes 组成的string
     * @param input
     * @param begin
     * @param end
     * @return
     */
    public static String removeBytes(String input,int begin,int end){
        byte[] bytes=input.getBytes();
        List<Byte> byteList=new ArrayList<>();
        for (int i = 0; i <bytes.length; i++) {
            if(i>=begin && i<=end){
                continue;
            }
            byte b=bytes[i];
            byteList.add(b);
        }
        int count=end-begin+1;
        byte[] bytesNew=new byte[bytes.length-count];
        for (int i = 0; i < byteList.size(); i++) {
            byte b=byteList.get(i);
            bytesNew[i]=b;
        }
        return new String(bytesNew);
    }

    /**
     * 根据传入csv文件，返回string list，
     * 忽略 表头所占的行，如果 表头数量为0，表示，不忽略表头
     * @param file
     * @param ignoreHeadLineCount 0表示无表头
     * @return
     */
    public static List<String> file2StringList(File file, int ignoreHeadLineCount){
        StringBuffer result =new StringBuffer() ;
        List<String> lineList=new ArrayList<>();
        int i=0;
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                if(i<ignoreHeadLineCount){
                    i++;
                    continue;
                }
                lineList.add(s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return lineList;
    }

    /**
     * 将List String 写入 outputFilePath 文件，以指定的 编码格式
     * @param stringList
     * @return
     */
    public static boolean stringList2File(List<String> stringList,String outputFilePath){
        File mifFile=new File(outputFilePath);
        boolean isSucess=false;
        try(FileOutputStream out=new FileOutputStream(mifFile);
            OutputStreamWriter osw=new OutputStreamWriter(out);
            BufferedWriter bw =new BufferedWriter(osw,50*1024*1024)){
            if(stringList!=null && !stringList.isEmpty()){
                for(String data : stringList){
//                    data= NslCharset.changeCharset(data,charset);
                    bw.append(data).append("\r").append("\n");
                }
            }
            isSucess=true;
        }catch (Exception e){
            isSucess=false;
        }
        return isSucess;
    }


}
